package com.onec.service.netty.coder;

import com.google.common.base.Utf8;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ReplayingDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 自定义整数解密器
 */
public class StringReplayingDecoder extends ReplayingDecoder<StringReplayingDecoder.PHASE> {

  enum PHASE {
    PHASE_1,
    PHASE_2,
  }

  private int length;
  private byte[] inByte;

  public StringReplayingDecoder() {
    super(PHASE.PHASE_1);
  }

  @Override
  protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    switch (state()) {
      case PHASE_1:
        length = in.readInt();
        inByte = new byte[length];
        checkpoint(PHASE.PHASE_2);
        break;
      case PHASE_2:

        in.readBytes(inByte, 0, length);
        out.add(new String(inByte, StandardCharsets.UTF_8));
        checkpoint(PHASE.PHASE_2);
        break;
      default:
        break;
    }

  }
}
